package com.hjw.dynamicdatasource.controller;

import com.hjw.dynamicdatasource.common.DataBaseType;
import com.hjw.dynamicdatasource.config.DynamicDataSourceManager;
import com.hjw.dynamicdatasource.mapper.EntInfoOrgtypeMapper;
import com.hjw.dynamicdatasource.service.DataSourceFactoryService;
import com.hjw.dynamicdatasource.service.DynamicService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @author ivan
 */
@Slf4j
@RestController
public class DataSourceController {

    @Autowired
    private DynamicDataSourceManager dataSourceManager;
    @Autowired
    private DataSourceFactoryService dataSourceFactoryService;
    @Autowired
    private EntInfoOrgtypeMapper entInfoOrgtypeMapper;
    @Autowired
    private DynamicService dynamicService;

    @PostMapping("/refresh")
    public String refreshDataSource(
            @RequestBody DatabaseRequest req) {
        log.info("刷新数据源，{}", req);
        try {
            DataBaseType dataBaseType;
            try {
                dataBaseType = DataBaseType.valueOf(DataBaseType.class,req.getType().toUpperCase());
            } catch (Exception e) {
                return "数据源类型错误：" + e.getMessage();
            }
            String urlTemplate = dataBaseType.getUrlTemplate()
                    .replace("{host}", req.getLocalhost())
                    .replace("{port}", req.getPort())
                    .replace("{database}", req.getDatabase());
            if (req.getSetting() != null){
                urlTemplate = urlTemplate.replace("{setting}", req.getSetting());
            }

            DataSource dataSource = dataSourceManager.refreshDataSource(urlTemplate, req.getUsername(), req.getPassword(), dataBaseType.getDriverClass());
            // 清除动态服务的缓存
            dynamicService.clearCache();
            dynamicService.setCurrentDataSourceKey(req.getLocalhost() +  req.getPort() +  req.getDatabase());
            return dataSourceFactoryService.refreshDataSource(dataSource);
        } catch (Exception e) {
            return "数据源刷新失败：" + e.getMessage();
        }
    }

    @GetMapping("/get")
    public String getDataSource() throws SQLException {
        return dataSourceManager.getDataSource().getConnection().getMetaData().getURL();
    }

    @GetMapping("/clear")
    public String clearDataSource() {
        dataSourceManager.clearDataSource();
        return "数据源清除成功";
    }




    @GetMapping("/get3")
    public String get3() {
        try {
            return entInfoOrgtypeMapper.selectById("wqeq17odb8ilHb8ECGtvdHWer9XqE4x").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Data
    public static class DatabaseRequest {
        private String localhost;
        private String port;
        private String database;
        private String setting;
        private String username;
        private String password;
        private String type;
    }
}